<?php
/**
 * 后台程序基类
 * @todo 整理到比如 Data_DB中
 */

class App_Background
{
    protected $smarty;

    function __construct()
	{
        $this->smarty = new Tool_Smarty(TEMPLATE_PATH);
	}

    function __get($name)
    {
        if ($name == '_user')
        {
            $this->$name = $this->_uid ? $this->user_info->getInfo($this->_uid, array('30','48','120')) : NULL;
            return $this->$name;
        }
        else if ($name === 'one')
        {
            return $this->data_one;
        }
        else if ($name === 'split')
        {
            return $this->data_split;
        }
        else if ($this->isMyObj($name))
        {
            $className = $this->getClassName($name);
            $this->$name = new $className;
            return $this->$name;
        }
        return NULL;
    }

	function run()
	{
		try
		{
			$this->getPara();
			$this->main();
		}
		catch(Exception $ex)
		{
			$this->showError($ex);
		}
	}

	protected function getPara()
	{
	}

	protected function readTable($table,$fields='*',$database=null,$host=null,$user=null,$pass=null)
	{
		// 参数
		$database = empty($database) ? DB_NAME : $database;
		$host = empty($host) ? DB_HOST : $host;
		$user = empty($user) ? DB_USER : $user;
		$pass = empty($pass) ? DB_PASS : $pass;

		// 连库		
		$db = new mysqli($host,$user,$pass,$database);
		if (!$db)
		{
			throw new Exception("Could not connect \'$host\' - " . mysqli_connect_error() );
		}

		if (!$db->query("set names 'utf8';"))
		{
			throw new Exception("Set Names 'utf8' Error - " . $db->errno .":". $db->error, $db->errno );
		}

		// 读取用户计数
		$sql = 'select '.$fields.' from '.$table;
		$res = $db->query($sql);
		$result = array();
		if (is_object($res) && $res->num_rows != 0)
		{
			while ($row = $res->fetch_array(MYSQLI_ASSOC))
			{
				$result[] = $row;
			}
		}
		return $result;
	}

    private function isMyObj($name)
    {
        //目录
        $name = strtolower($name);
        $arr = explode('_', $name);
        if(empty($arr))
        {
            return false;
        }
        $dir = $arr[0];

        //文件
        $className = implode('_', array_map('ucfirst',$arr));
        $classFile = INCLUDE_PATH . $dir . DS . $className . '.php';
        if (is_file($classFile))
        {
            return true;
        }
        return false;
    }

    private function getClassName($name)
    {
        //目录
        $name = strtolower($name);
        $arr = explode('_', $name);
        if(empty($arr))
        {
            return false;
        }

        //文件
        $className = implode('_', array_map('ucfirst',$arr));
        return $className;
    }

	protected function showError($ex)
	{
		$error = "[".$ex->getCode()."]: ".$ex->getMessage();
		if ($ex->reason)
		{
			$error .= ' '.$ex->reason;
		}

		echo $error."\n";
		print_r($ex->getTrace());
		echo "\n";
	}
}
?>
